package com.example.demo.proxy;


import org.springframework.cglib.proxy.Enhancer;

//import net.sf.cglib.proxy.Enhancer;//如果使用这个包,需要添加vm option

import java.lang.reflect.Proxy;

public class Main {
    public static void main1(String[] args) {
        //静态代理
        HouseProxy proxy = new HouseProxy(new RealHouseSubject());
        proxy.rent();
    }

    public static void main2(String[] args) {
        //JDK动态代理
        HouseSubject target = new RealHouseSubject();

        //运行时,创建代理对象
        //写法1
//        HouseSubject proxy = (HouseSubject) Proxy.newProxyInstance(target.getClass().getClassLoader(),
//                new Class[]{HouseSubject.class},new JDKInvocation(target));
        //写法2
        HouseSubject proxy = (HouseSubject) Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(),new JDKInvocation(target));
        proxy.rent();
        proxy.sale();
    }

    public static void main(String[] args) {
        //CGLib动态代理
        HouseSubject target = new RealHouseSubject();
        //运行时, 动态代理创建对象
        //如果使用CGlib运行的话, 需要添加vm option
        //--add-opens java.base/java.lang=ALL-UNNAMED
        HouseSubject proxy = (HouseSubject) Enhancer.create(target.getClass(),
                new CGLibMethodInterceptor(target));
        proxy.rent();
    }
}
